package cn.itsource.org.service.impl;

import cn.itsource.basic.config.exception.BusinessException;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.basic.util.PageList;
import cn.itsource.basic.util.TreeUtil;
import cn.itsource.org.pojo.domain.Department;
import cn.itsource.org.mapper.DepartmentMapper;
import cn.itsource.org.query.DepartmentQuery;
import cn.itsource.org.service.IDepartmentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department,DepartmentQuery> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;


    @Override
    @Transactional// 事务管理
    public void saveOrUpdate(Department department) {

        //把之前的dirPath留下来 /3/8
        String oldDirPath = department.getDirPath();

        //代码细节1，参数验证
        if (StringUtils.isBlank(department.getName())){
            throw new BusinessException("部门名称不能为空");
        }
        if (StringUtils.isBlank(department.getSn())){
            throw new BusinessException("部门编号不能为空");
        }

        //没有主键id就是新增操作，否则就是修改操作
        if (department.getId() == null){
            /**
             * 前端传递parentIds的是[3,8,10]
             * 效果
             *    parent_id  =  10
             *    加入新增这条数据的主键是15，dirPath = /3/8/10/15
             *      //1.获取到主键id
             *
             */
            //只有设置了值得字段才会被新增
            departmentMapper.insertSelective(department);

            //调用方法
            makeTree(department);
            //设置了值得字段才会被修改
            departmentMapper.updateByPrimaryKeySelective(department);
        }else{
            //调用方法
            String newDirPath = makeTree(department);
            //设置了值得字段才会被修改
            departmentMapper.updateByPrimaryKey(department);

            //1.通过老path 模糊查询                                          /3/8
            List<Department> departments = departmentMapper.findByOldPath(oldDirPath);

            //2.替换 //拿到了  /3/8/9  /3/8/10
            for (Department department1 : departments) {
                if (newDirPath != null){
                    // /3/8    /1/8
                    String finalPath = department1.getDirPath().replace(oldDirPath,newDirPath);
                    // /1/8/9  /1/8/10
                    department1.setDirPath(finalPath);
                    //3.修改
                    departmentMapper.updateByPrimaryKeySelective(department1);
                }
            }
        }
    }

    /**
     * alt+shift+m ：抽取方法
     */
    private String makeTree(Department department) {
        Long[] parentIds = department.getParentIds();

        List<Long> longList = Arrays.asList(parentIds);
        boolean contains = longList.contains(department.getId());
        if (contains){
            throw new BusinessException("不能选择自己为自己的上级");
        }


        //这种是有上级的情况
        if (parentIds != null && parentIds.length > 0) {
            //1.获取数组的最后一位
            Long parentId = parentIds[parentIds.length - 1];
            //2.设置字段的值
            department.setParentId(parentId);

            //3.遍历上级部门数据 [3,8,10]  活学活用
            StringBuilder dirPath = new StringBuilder("");
            for (Long id : parentIds) {
                dirPath.append("/").append(id);
            }
            dirPath.append("/").append(department.getId());
            //4.设置dirPath字段的值
            department.setDirPath(dirPath.toString()); // /1/8

            return dirPath.toString();

        } else {
            //parentIds:null []
            //主键16   parentId = null  dirPath = /16
            //4.更新dirPath字段
            department.setDirPath("/" + department.getId());
            department.setParentId(null);

            return "/" + department.getId();
        }


    }

    public static void main(String[] args) {
        List<String> strings = Arrays.asList("/3/8/9", "/3/8/10", "/3/8/10/11");

        for (String string : strings) {
            System.out.println(string.replace("/3/8", "/1/8"));
        }
    }


    /**
     * 分页查询
     * @param query
     * @return
     */
    @Override
    public PageList<Department> findPage(DepartmentQuery query) {

        //1.使用分页工具类
        PageHelper.startPage(query.getPage(), query.getSize());
        //2.执行查询
        List<Department> departments = departmentMapper.findPage(query);

        //3.封装结果
        PageInfo<Department> pageInfo = new PageInfo<>(departments);

        //4.封装我的自定义对象
        PageList<Department> pageList = new PageList<>(pageInfo.getTotal(), pageInfo.getList());

        return pageList;
    }

    @Override
    public List<Department> findParentDepts() {
        return departmentMapper.findParentDepts();
    }



    @Override
    public List<Department> treeDept() {

        //1.查询所有
        List<Department> departments = departmentMapper.selectAll();

        //2.使用工具类方法
        List<Department> list = TreeUtil.getTree(departments);

        return list;
    }
}